package grouuu.input ;

import openfl.display.Stage;
import openfl.events.KeyboardEvent;
import openfl.ui.Keyboard;

/**
 * ...
 * @author Grouuu
 */
class Key
{
	public var keyPressed(default, null):Array<UInt>;
	
	public var LEFT(get, null):Bool;
	public var UP(get, null):Bool;
	public var RIGHT(get, null):Bool;
	public var DOWN(get, null):Bool;
	
	private var stage:Stage;

	public function new(stage:Stage) 
	{
		this.stage = stage;
		
		keyPressed = [];
	}
	
	// CONTROL ////////////////////////////////////////////////////////////////////////////////////
	
	public function start():Void
	{
		stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
	}
	
	public function stop():Void
	{
		stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
		
		keyPressed = [];
	}
	
	public function add(code:UInt):Void
	{
		if (keyPressed.indexOf(code) == -1)
			keyPressed.push(code);
	}
	
	public function remove(code:UInt):Void
	{
		if (keyPressed.indexOf(code) != -1)
			keyPressed.splice(keyPressed.indexOf(code), 1);
	}
	
	// GETTER /////////////////////////////////////////////////////////////////////////////////////
	
	private function get_LEFT():Bool
	{
		return (is(Keyboard.LEFT) || is(Keyboard.Q));
	}
	
	private function get_UP():Bool
	{
		return (is(Keyboard.UP) || is(Keyboard.Z));
	}
	
	private function get_RIGHT():Bool
	{
		return (is(Keyboard.RIGHT) || is(Keyboard.D));
	}
	
	private function get_DOWN():Bool
	{
		return (is(Keyboard.DOWN) || is(Keyboard.S));
	}
	
	// EVENT //////////////////////////////////////////////////////////////////////////////////////
	
	private function onKeyDown(e:KeyboardEvent):Void
	{
		add(e.keyCode);
	}
	
	private function onKeyUp(e:KeyboardEvent):Void
	{
		remove(e.keyCode);
	}
	
	// UTIL ///////////////////////////////////////////////////////////////////////////////////////
	
	private function is(code):Bool
	{
		return keyPressed.indexOf(code) != -1;
	}
}